﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using RkLib.WinApi;
using RkLib.Configuration;
namespace CodeCollection
{
    public  class TvOp
    {
        private const string CM_ADD_FILE = "Add File";
        private const string CM_ADD_FOLDER = "Add Folder";
        private const string CM_REFRESH = "Refresh";
        private const string CM_DELETE = "Delete";
        private const string CM_RENAME = "Rename";

        private const int IMAGE_IDX_FOLDER = 0;
        private const int IMAGE_IDX_FILE = 1;

        private IntPtr MsgHwnd = IntPtr.Zero;
        private TreeView tView = null;
        private string SrcDir = null;
        private ImageList ImgLst = null;
        
        public TvOp(TreeView tv,IntPtr msgHand,string srcDir)
        {
            MsgHwnd = msgHand;
            tView = tv;
            SrcDir = srcDir;
            CmInit();
            tView.NodeMouseDoubleClick +=new TreeNodeMouseClickEventHandler(tView_NodeMouseDoubleClick);
            tView.AfterLabelEdit += new NodeLabelEditEventHandler(tView_AfterLabelEdit);
            tView.NodeMouseClick += new TreeNodeMouseClickEventHandler(tView_NodeMouseClick);
            tView.LabelEdit = true;
            ImgLst = new ImageList();
            ImgLst.Images.Add(CodeCollection.Properties.Resources.png_folder);
            ImgLst.Images.Add(CodeCollection.Properties.Resources.png_file);
            tView.ImageList = ImgLst;
        }
        public void Refresh()
        {
            tView.BeginUpdate();
            tView.Nodes.Clear();
            AddFolderToNode(null, SrcDir);
            tView.EndUpdate();
        }
        public void DisplayLstFile()
        {
            string LstFile = Cfg.ReadString(gValue.SFT_SEC_CFG, gValue.SFT_LST_DIS_FILE, "");
            Win32Api.SendMessage(MsgHwnd, (int)WM_MSG.WM_DISPLAY_CODE, IntPtr.Zero, LstFile);
        }


        private void AddFolderToNode(TreeNode pNode,string dir)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(dir);
            if (null == pNode)
            {
                pNode = new TreeNode();
                pNode.Text = dirInfo.Name;
                pNode.ImageIndex = IMAGE_IDX_FOLDER;
                pNode.SelectedImageIndex = IMAGE_IDX_FOLDER;
                tView.Nodes.Add(pNode);
            }
            
            foreach (var subDir in dirInfo.GetDirectories())
            {
                if ((subDir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    continue;
                }
                TreeNode sNode = new TreeNode();
                sNode.Text = subDir.Name;
                pNode.Nodes.Add(sNode);
                AddFolderToNode(sNode, subDir.FullName);
            }
            foreach (var file in Directory.GetFiles(dir))
            {
                TreeNode sNode = new TreeNode();
                if (Path.GetExtension(file).ToLower() != gValue.CODE_FILE_EXTENSION)
                {
                    continue;
                }
                sNode.Text = Path.GetFileNameWithoutExtension(file);
                sNode.ImageIndex = IMAGE_IDX_FILE;
                sNode.SelectedImageIndex = IMAGE_IDX_FILE;
                pNode.Nodes.Add(sNode);
            }
        }

        private void tView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = e.Node;
            if (node.Nodes.Count > 0)
            {
                return;
            }
            string FilePath = GetNodePath(node);
            Win32Api.SendMessage(MsgHwnd, (int)WM_MSG.WM_DISPLAY_CODE, IntPtr.Zero, FilePath);
        }
        private void tView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            TreeNode node = e.Node;
            if (null == e.Label)
            {
                return;
            }
            string src = GetNodePath(node);
            string dst;
            if (NodeIsFile(node))
            {
                dst = Path.GetDirectoryName(src) + "\\" + e.Label + gValue.CODE_FILE_EXTENSION;
                File.Move(src, dst);

            }
            else
            {
                DirectoryInfo dirInfo = new DirectoryInfo(src);
                dst = dirInfo.Parent.FullName + "\\" + e.Label;
                Directory.Move(src, dst);
            }
            node.EndEdit(true);
        }
        private void tView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                tView.SelectedNode = e.Node;
            }
        }
        private string GetNodePath(TreeNode node)
        {
            string strPath = Path.GetDirectoryName(gValue.SrcCodeDir) + "\\" + node.FullPath;
            if (!Directory.Exists(strPath))
            {
                strPath += gValue.CODE_FILE_EXTENSION;
            }
            return strPath;
        }
        private bool NodeIsFile(TreeNode node)
        {
            return PathIsFile(GetNodePath(node));
        }
        private bool PathIsFile(string str)
        {
            return File.Exists(str) ;
        }
        private bool NodeHasSpecNode(TreeNode node, string str)
        {
            for (int idx = 0; idx < node.Nodes.Count; idx++)
            {
                if (node.Nodes[idx].Text == str)
                {
                    return true;
                }
            }
            return false;
        }
        private string GetNewNode(TreeNode node, string str)
        {
            int idx = 0;
            if (!NodeHasSpecNode(node, str))
            {
                return str;
            }
            idx++;
            while (NodeHasSpecNode(node, str + idx))
            {
                idx++;
            }
            return str + idx;
        }
#region ContextMune
        ContextMenuStrip CM;
        private void CmInit()
        {
            CM = new ContextMenuStrip();
            ToolStripItem toolStrip =  CM.Items.Add(CM_REFRESH);
            toolStrip.Click += new EventHandler(toolStrip_Refresh);
            toolStrip = CM.Items.Add(CM_ADD_FILE);
            toolStrip.Click += new EventHandler(toolStrip_AddFile);
            toolStrip = CM.Items.Add(CM_ADD_FOLDER);
            toolStrip.Click += new EventHandler(toolStrip_AddFolder);
            toolStrip = CM.Items.Add(CM_RENAME);
            toolStrip.Click += new EventHandler(toolStrip_Rename);
            toolStrip = CM.Items.Add(CM_DELETE);
            toolStrip.Click += new EventHandler(tollStrip_Delete);
            tView.ContextMenuStrip = CM;
        }
        private void toolStrip_Refresh(object sender, EventArgs e)
        {
            this.Refresh();
        }
        private void toolStrip_AddFile(object sender, EventArgs e)
        {
            TreeNode node = tView.SelectedNode;
            if (NodeIsFile(node))
            {
                node = node.Parent;
            }
            string strPath = GetNodePath(node);
            string strName = GetNewNode(node, gValue.NEW_FILE);
            node = node.Nodes.Add(strName);
            strPath += "\\" + strName + gValue.CODE_FILE_EXTENSION;
            PublicFunction.WriteCodeToFile(strPath, "");
            node.BeginEdit();
        }
        private void toolStrip_AddFolder(object sender, EventArgs e)
        {
            TreeNode node = tView.SelectedNode;
            if (NodeIsFile(node))
            {
                return;
            }
            string strPath = GetNodePath(node);
            string strName = GetNewNode(node, gValue.NEW_DIR);
            node = node.Nodes.Add(strName);
            strPath += "\\" + strName;
            PublicFunction.CreateFolder(strPath);
            node.BeginEdit();
        }
        private void toolStrip_Rename(object sender, EventArgs e)
        {
            TreeNode node = tView.SelectedNode;
            if (node == tView.Nodes[0])
            {
                return;
            }   
            node.BeginEdit();
        }
        private void tollStrip_Delete(object sender, EventArgs e)
        {
            TreeNode node = tView.SelectedNode;
            if (node == tView.Nodes[0])
            {
                return;
            }
            string strPath = GetNodePath(node);
            if (MessageBox.Show("是否要删除?", "提醒", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                PublicFunction.DeletePath(strPath);
                node.Remove();
            }

        }
        private void CM_SetItemEnable(string itemName, bool enable)
        {
            foreach(ToolStripItem toolStrip in CM.Items)
            {
                if (toolStrip.Text == itemName)
                {
                    toolStrip.Enabled = enable;
                }
            }
        }
#endregion


    }
}
